<template>
  <el-form :model="loginForm" label-width="80px">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="loginForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="loginForm.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm()">登录</el-button>
      <el-button @click="resetForm()">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>

import { ElMessage } from 'element-plus'
import { reactive } from 'vue'
import { useRouter } from 'vue-router';
export default {
  setup() {
    const router = useRouter();
    const loginForm = reactive({
        username: '',
        password: ''
      })
    const submitForm = async () => {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginForm)
      })
      const data = await response.json();
      if (data.token) {
        sessionStorage.setItem('x-token', data.token);
        router.push('/mail');
      } else {
        ElMessage({
          message: data.message,
          type: 'error',
        })
        throw new Error('Login failed');  // 登录失败抛出错误

      }

    

    };
    const resetForm = () => {
      loginForm.username = ''
      loginForm.password = ''
    }
    return {
      loginForm,
      resetForm,
      submitForm
    }
  }
}
</script>